package com.ht.api.task.ad;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.sql.DataSource;

import cn.hutool.core.util.RandomUtil;
import com.ht.api.db.Db;
import com.ht.api.db.DbConfig;
import com.ht.api.db.DbList;
import com.ht.api.db.Entity;
import com.ht.api.db.task.HtTaskExecutor;
import com.ht.api.db.task.Plan;
import com.ht.api.db.task.TaskHandler;
import com.ht.api.db.util.HtUtil;
import com.ht.api.open.OpenUtil;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ht.api.service.WwxService;
import lombok.extern.slf4j.Slf4j;

/**
 * 发送朋友圈任务
 */
@Slf4j
public class SendMomentTask implements TaskHandler {

    /** 接口ID：发送朋友圈 */
    protected static final long API_ID = 1892041255978930176L;

	@Override
	public String getName() {
		return "发送朋友圈任务";
	}

    @Override
    public boolean handler(JSONObject requestParam, String groupId, long taskId) {
        long tenantId = requestParam.getLong("tenant_id");
        DataSource ds = DbConfig.useTenantDb(tenantId);

        String adTaskGroupId = requestParam.getStr("ad_task_group_id");
        String appid = requestParam.getStr("appid");
        JSONArray tagids = requestParam.getJSONArray("tagids");


        Entity adTaskGroup = Db.createSqlParser("ad_task_group").where("main_id", adTaskGroupId).findOne(ds);
        String content = adTaskGroup.getStr("creative_content");

        DbList momentUserList = Db.createSqlParser("wx_moment_user").select("userid").where("ad_task_group_id", adTaskGroupId).query(ds);

        List<String> touchList = new ArrayList<>();
        for (Entity momentUser : momentUserList) {
            touchList.add(momentUser.getStr("userid"));
        }

        JSONObject param = JSONUtil.createObj();
        param.set("text.content", content);
        param.set("visible_range.sender_list.user_list", touchList);

        if (tagids != null && tagids.size() > 0) {
            param.set("visible_range.external_contact_list.tag_list", tagids);
        }

        String creativeId = adTaskGroup.getStr("creative_id");
        Entity creative = Db.createSqlParser("creative").where("main_id", creativeId).findOne(ds);

        JSONArray materials = creative.getJSONArray("material");

        if (materials != null) {
            int imageIndex = 0;
            for (int i = 0; i < materials.size(); i++) {
                JSONObject material = materials.getJSONObject(i);
                String type = material.getStr("type");

                switch (type) {
                    case "image":

                        String imageMediaId = WwxService.getAttachmentImageMediaId(appid, material.getStr("url"));

                        param.set("attachments["+imageIndex+"].msgtype", "image");
                        param.set("attachments["+imageIndex+"].image.media_id", imageMediaId);
                        imageIndex++;

                        break;

                    case "video":
                        String videoMediaId = WwxService.getAttachmentVideoMediaId(appid, material.getStr("url"));

                        param.set("attachments[0].msgtype", "video");
                        param.set("attachments[0].video.media_id", videoMediaId);

                        break;

                    case "link":
                        String view = material.getStr("view");
                        if (view.equals("card")) {
                            String linkId = material.getStr("link_id");
                            Entity link = Db.createSqlParser("short_link").where("main_id", linkId).findOne(ds);

                            String state = getRandomCode(ds);
                            Entity shortLinkState = Entity.create("short_link_state");
                            shortLinkState.set("link_id", linkId);
                            shortLinkState.set("state", state);
                            shortLinkState.set("context", adTaskGroup.get("context"));
                            shortLinkState.set("appid", adTaskGroup.getStr("appid"));

                            Db.insert(ds, shortLinkState);

                            String url = "http://m.htiannet.com/l/" + state;

                            String relationId = link.getStr("relation_id");
                            String relationTable = link.getStr("relation_type");

                            Entity relation = Db.createSqlParser(relationTable).where("main_id", relationId).findOne(ds);
                            String iconUrl = "";
                            String title = "";
                            if (relationTable.equals("lesson")) {
                                iconUrl = relation.getStr("cover_image");
                                title = relation.getStr("name");
                            } else if  (relationTable.equals("live")) {
                                iconUrl = relation.getStr("cover_image");
                                title = relation.getStr("name");
                            } else if  (relationTable.equals("questionnaire")) {
                                iconUrl = relation.getStr("cover_image");
                                title = relation.getStr("name");
                            } else if  (relationTable.equals("product")) {
                                iconUrl = relation.getStr("main_image");
                                title = relation.getStr("name");
                            } else if  (relationTable.equals("writings")) {
                                iconUrl = relation.getStr("cover_image");
                                title = relation.getStr("title");
                            }

                            String linkImageMediaId = WwxService.getAttachmentImageMediaId(appid, iconUrl);

                            param.set("attachments[2].msgtype", "link");
                            param.set("attachments[2].link.title", title);
                            param.set("attachments[2].link.url", url);
                            param.set("attachments[2].link.media_id", linkImageMediaId);
                        }

                        break;

                }

            }
        }

        log.info(param.toStringPretty());

        String str = OpenUtil.call(appid, API_ID, param);

        JSONObject result = JSONUtil.parseObj(str);
        String jobid = result.getStr("jobid");

        JSONObject checkMomentStatusParam = JSONUtil.createObj();
        checkMomentStatusParam.set("appid", appid);
        checkMomentStatusParam.set("jobid", jobid);
        checkMomentStatusParam.set("tenant_id", tenantId);
        checkMomentStatusParam.set("ad_task_group_id", adTaskGroupId);

        HtTaskExecutor.submitTask(checkMomentStatusParam, new CheckMomentStatusTask(),
                Plan.create().setMin(5).setTimes(3, TimeUnit.MINUTES));//当前开始执行，每隔5秒钟执行一次，3分钟后结束

        adTaskGroup.set("business_relation_id", jobid);
        Db.insert(ds, adTaskGroup);

        log.info("发送朋友圈 success......");


        return true;
    }

    /**
     * 生成一个随机code，并确保此code在short_link表中不存在
     * @param ds 数据源
     * @return
     */
    private static String getRandomCode(DataSource ds) {
        String code = RandomUtil.randomString(7);

        // 查询数据库，如果存在，则递归操作
        boolean exists = Db.createSqlParser("short_link").where("code", code).hasRow(ds);
        if (exists) {
            return getRandomCode(ds);
        }

        return code;
    }
}
